import _ from "lodash";

import service from "@service";

const fileBasePath = process.env.VUE_APP_FILE_BASE_PATH; // "http://10.21.19.51:8888/";

export const getFileFullPath = (filePath) => {
    return `${fileBasePath}${filePath}`;
};

// video/mp4 image/png image/jpeg image/jpg audio/mp3

const fileAcceptList = [ 
    "video/mp4",
    "image/png",
    "image/jpeg",
    "image/jpg",
    "audio/mp3",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
   
];

const videoRegex = /(video\/|)mp4/;
const audioRegex = /(audio\/|)mp3/;
const imageRegex = /(image\/|)(png|jpeg|jpg)/;
const excelRegex = /(application\/|)(vnd\.ms\-excel|vnd\.openxmlformats\-officedocument\.spreadsheetml\.sheet)/;
//const fileRegex = /(application\/|)(vnd\.ms\-excel|vnd\.openxmlformats\-officedocument\.spreadsheetml\.sheet)/;
const typeMap = {
    image: { regex: imageRegex },
    audio: { regex: audioRegex },
    video: { regex: videoRegex },
    excel: { regex: excelRegex },
   // files: {regex:fileRegex}  
};

export const getFileAcceptListByType = (type) => {
    return fileAcceptList.filter((v) => typeMap[type].regex.test(v));
};

export const getFileAccept = () => fileAcceptList.join(",");

export const getSuffixByFileName = (fileName) => {
    let splitList = (fileName || "").split(".");

    return splitList[splitList.length - 1];
};

export const isVideoByFileName = (fileName) => {
    let suffix = getSuffixByFileName(fileName);

    return videoRegex.test(suffix);
};

export const isVideoByType = (type) => {
    return videoRegex.test(type);
};

export const isAudioByType = (type) => {
    return audioRegex.test(type);
};

export const isAudioByFileName = (fileName) => {
    let suffix = getSuffixByFileName(fileName);

    return audioRegex.test(suffix);
};

export const fileUploadHandle = ({
    fileKey='file',
    fileType,
    accept,
    serviceName = 'fileFileUpload',
    params = {},
    onSuccess,
    onError,
    onProcess,
    onFileSelected, // 选择文件钩子函数，会把文件传进去，返回false  会停止上传
    onRequestSuccess,
    beforeUpload,
} = {}) => {
    if (!accept) {
       if(fileType ==="link"){
             accept= ".rar,.zip,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.png,.jpeg,.jpg,.mp4,.avi,.flv";
       }else{
            let tempFileAcceptList = fileAcceptList;
            if (fileType === "image") {
                tempFileAcceptList = tempFileAcceptList.filter((v) =>
                    /^image/.test(v)
                );
            } else if (fileType === "video") {
                tempFileAcceptList = tempFileAcceptList.filter((v) =>
                    /^video/.test(v)
                );
            } else if (fileType === "media") {
                tempFileAcceptList = tempFileAcceptList.filter((v) =>
                    /^(video|image|audio)/.test(v)
                );
            }
            accept = tempFileAcceptList.join(",");
        }
    }

    const uploadSet = {};

    let fileInput = document.createElement("input");

    fileInput.setAttribute("type", "file");
    fileInput.setAttribute("accept", accept);
    fileInput.classList.add("ql-image");

    fileInput.addEventListener("change", async () => {

        if (fileInput.files != null && fileInput.files[0] != null) {
            let file = fileInput.files[0];
            let nextFlag = true; // 是否继续流程
            if(onFileSelected) {
                nextFlag = onFileSelected(fileInput.files)
            }
            if(!nextFlag) return;
            let forms = new FormData();

            forms.append(fileKey, file);
            if (params) {
                Object.keys(params).forEach(k => {
                    forms.append(k, params[k]);
                })
            }
            const next = async () => {
                const loading = await window.g_instance.$store.dispatch("global/loading")
                let result = await service(serviceName, {
                    data: forms,
                    timeout:30000,
                    onUploadProgress: (progressEvent) => {
                        let complete =
                            ((progressEvent.loaded / progressEvent.total) * 100) |
                            0;
                        onProcess && onProcess(complete);
                    },
                }).catch((err) => {
                    loading.close();
                    console.log("upload err", err);
                    return null;
                });
                loading.close();
                let outFileInfo = {};

                outFileInfo.fileId = _.get(result, "ATTACH.fileId");

                onRequestSuccess && onRequestSuccess(result);
                if (outFileInfo.fileId) {
                    outFileInfo.filePath = _.get(result, "ATTACH.fileNm");
                    outFileInfo.fileName = _.get(result, "ATTACH.fileNm");
                    outFileInfo.fileClass = getSuffixByFileName(
                        outFileInfo.fileName
                    );

                    onSuccess && onSuccess(outFileInfo);
                } else {
                    onError && onError(new Error("upload error"));
                }
            
                console.log("result", file, result, outFileInfo);

            }
            if(beforeUpload) {
                beforeUpload(forms, next, fileInput.files)
            }else {
                next()
            }
        } else {
            onError && onError(new Error("no select"));
        }
        document.body.removeChild(fileInput);
    });
    fileInput.style.display = "none";

    document.body.appendChild(fileInput);

    fileInput.click();

    return uploadSet;
};

const sizeUnitArray = ["KB", "MB", "GB", "PB"];

export const getFileSizeName = (size, { fixed = 2 } = {}) => {
    if (typeof size === "string") {
        size = parseInt(size, 10);
    }
    let count = -1;
    while (size >= 1024 && count + 2 < sizeUnitArray.length) {
        size /= 1024;
        count++;
    }
    return `${size.toFixed(fixed)}${count > -1 ? sizeUnitArray[count] : "B"}`;
};

//获取文件名后缀名
const getExtension = str => {
    let ext = null;
    let name = str.toLowerCase();
    let i = name.lastIndexOf(".");
    if (i !== -1) {
        ext = name.substring(i);
    }
    return ext;
};
export const imgExt = ['JPG', 'JPEG', 'PNG', 'GIF',]
export const getIsImageByFileName = fileName => {
    //判断是否图片文件
    let ext = getExtension(fileName);
    return imgExt.indexOf(ext) !== -1;
};

// zsk图片预览地址
export const getPreviewPath = (module, fileId) => {
    let pathMap = {
        zsk: "/zskServer/kc/doc/managesvc/msa/iomoreimgcom"
    }
    let path = pathMap[module] + "?fileId=" + fileId;

    return path;
}
// zsk下载路径
export const getDownloadPath = (module, fileId,fileName) => {
    let pathMap = {
        zsk: "/zskServer/kc/doc/managesvc/msa/umeditorfiles/download"
    }
    let path = pathMap[module] + "?fileId=" + fileId+'&fileName='+fileName;

    return path;
}
